package crp.core.workflow.domain.services;

import crp.core.shared.LifecycleStatus;
import crp.core.workflow.domain.messages.WorkflowMessages;
import crp.core.workflow.domain.models.CreateWorkflowInstanceCommand;
import crp.core.workflow.domain.models.DoneWorkflowTaskCommand;
import crp.core.workflow.domain.models.WorkflowModelEntity;
import crp.core.workflow.domain.models.WorkflowTaskEntity;
import crp.core.workflow.domain.repositories.WorkflowModelRepository;
import crp.core.workflow.domain.repositories.WorkflowTaskRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class WorkflowCommandCreator {
    private final WorkflowModelRepository modelRepository;
    private final WorkflowTaskRepository workflowTaskRepository;
    private final WorkflowEngine workflowEngine;

    @Inject
    public WorkflowCommandCreator(WorkflowModelRepository modelRepository,
                                  WorkflowTaskRepository workflowTaskRepository,
                                  WorkflowEngine workflowEngine) {
        this.modelRepository = modelRepository;
        this.workflowTaskRepository = workflowTaskRepository;
        this.workflowEngine = workflowEngine;
    }

    public CreateWorkflowInstanceCommand.CreateWorkflowInstanceCommandBuilder createInstanceCommand(String topic, String externalId) {
        WorkflowModelEntity model = modelRepository.findByTopic(topic, LifecycleStatus.ENABLED)
                .orElseThrow(() -> WorkflowMessages.INSTANCE.modelNotFound(topic));
        return CreateWorkflowInstanceCommand.builder()
                .model(model)
                .externalId(externalId);
    }

    public DoneWorkflowTaskCommand.DoneWorkflowTaskCommandBuilder createDoneTaskCommand(String taskId) {
        WorkflowTaskEntity task = workflowTaskRepository.findById(taskId);
        return DoneWorkflowTaskCommand.builder().task(task)
                .nextNode(workflowEngine.nextTaskNode(task.getInstance(), task));
    }
}
